package list;

public class LeetCode2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = null, p3 = null;

        int a = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;

            int sum = n1 + n2 + a;
            if (res == null) {
                res = p3 = new ListNode(sum % 10);
            } else {
                p3.next = new ListNode(sum % 10);
                p3 = p3.next;
            }
            a = sum / 10;

            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (a > 0) {
            p3.next = new ListNode(a);
        }
        return res;
    }
}
